package cn.wolfcode.wms.service.impl;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import cn.wolfcode.wms.domain.Permission;
import cn.wolfcode.wms.mapper.PermissionMapper;
import cn.wolfcode.wms.query.PageResult;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.IPermissionService;
import cn.wolfcode.wms.util.RequiredPermission;

@Service
public class PermissionServiceImpl implements IPermissionService {

	@Autowired
	private ApplicationContext ctx;

	@Autowired
	private PermissionMapper mapper;

	@Override
	public void delete(Long id) {
		mapper.delete(id);
	}

	@Override
	public List<Permission> list() {
		return mapper.list();
	}

	@Override
	public PageResult query(QueryObject qo) {
		int totalCount = mapper.queryForCount(qo);
		if (totalCount == 0) {
			return new PageResult(qo.getPageSize());
		}
		List<Permission> listData = mapper.queryForList(qo);
		return new PageResult(qo.getCurrentPage(), qo.getPageSize(), listData, totalCount);
	}

	@Override
	public void load() {
		// 查询出所有的全限表达式
		List<String> expressions = mapper.selectExpression();
		// 获取容器中的所有的Controller对象
		// 所有Controller类上都贴了Controller注解
		Map<String, Object> beansWithAnnotation = ctx.getBeansWithAnnotation(Controller.class);
		// 从集合中获取到所有的Controller对象
		Collection<Object> controllers = beansWithAnnotation.values();
		for (Object object : controllers) {
			// 获取当前Controller中的所有方法
			Method[] methods = object.getClass().getMethods();
			for (Method method : methods) {
				// 判断方法上是否贴了RequiredPermission注解
				if (method.isAnnotationPresent(RequiredPermission.class)) {
					// 获取当前方法所在Controller类的全限定名
					String className = object.getClass().getName();	
					// 获取方法的名称
					String methodName = method.getName();
					// 拼接全限表达式
					String expression = className + ":" + methodName;
					// 获取注解的参数:权限的名称
					String name = method.getAnnotation(RequiredPermission.class).value();
					// 保存之前先判断当前表达式是否在数据库中存在
					// 不存在:保存
					if (!expressions.contains(expression)) {
						Permission permission = new Permission();
						permission.setName(name);
						permission.setExpression(expression);
						mapper.save(permission);
					}
				}	
			}
		}
	}
}
